class Solution {
    struct compare
    {
        bool operator()(const pair<int, int>& x, const pair<int, int>& y)
        {
            return x.second > y.second;
        }
    };
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> hash;
        for (auto e : nums) hash[e]++;
        priority_queue<pair<int, int>, vector<pair<int, int>>, compare> pq;
        for (auto e : hash)
        {
            pq.push(e);
            if (pq.size() > k) pq.pop();
        }
        vector<int> ans;
        while (!pq.empty())
        {
            ans.push_back(pq.top().first);
            pq.pop();
        }
        return ans;
    }
};